<template>
  <div class="showTable" ref="showTable">
    <el-row id="conditionGroup" class="condition">
      <ConditionGroup :plantList="plantList" @queryUnitList="queryUnitList" @exportUnitList="exportUnitList" :model="model" :selectedList="selectedList" @resetSelectedRow="resetSelectedRow" />
    </el-row>
    <el-row id="table" class="table">
      <el-table v-loading="tableLoading" :data="tableData" style="width: 100%" stripe  border :height="tableHeight" @selection-change="handleSelectionChange" >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="PLANT_NAME" label="所属电厂" width="150" align="center" />
        <el-table-column prop="UNIT_NAME" label="机组名称" width="150" align="center" />
        <el-table-column prop="YEAR_TYPE_T" label="类型" width="150" align="center" />
        <el-table-column width="360" label="发电类型" align="center" >
          <el-table-column prop="GENERATOR1" label="一级" width="120" align="center" />
          <el-table-column prop="GENERATOR2" label="二级" width="120" align="center"/>
          <el-table-column prop="GENERATOR3" label="三级" width="120" align="center"/>
        </el-table-column>
        <el-table-column width="360" label="基本参数" align="center">
          <el-table-column prop="CAPACITY" label="机组容量" width="150" align="center"/>
          <el-table-column prop="RUN_DATE" label="运行时间" width="120" align="center"/>
          <el-table-column prop="FIX_HOURS" label="年度检修时长（小时）" width="120" align="center"/>
        </el-table-column >
        <el-table-column prop="PERIODS" label="年份" width="150" align="center" />
        <el-table-column width="360" :label="getMonth(i)+'月'" align="center" v-for="i of 12" :key="i">
          <el-table-column :prop="'EXPECT_POWER_' + i" label="预想出力" width="120" align="center"/>
          <el-table-column :prop="'AVERAGE_POWER_' + i" label="平均出力" width="120" align="center"/>
          <el-table-column :prop="'FORCED_POWER_' + i" label="强迫出力" width="120" align="center"/>
        </el-table-column>
        <el-table-column prop="USE_STATUS_T" label="状态" width="80" align="center" />
      </el-table>
    </el-row>
    <el-row id="tablePagination" class="page">
      <TablePagination @queryUnitList="queryUnitList" />
    </el-row>
    <AddSet :plantList="plantList" v-show="visibleDia" :model="model" @queryUnitList="queryUnitList" @resetSelectedRow="resetSelectedRow"/>
  </div>
</template>

<script setup>
import ConditionGroup from '@/views/stagePower/ConditionGroup';
import TablePagination from '@/views/stagePower/TablePagination';
import AddSet from '@/views/stagePower/AddSet';
import { copyAttr, getMonth, resetObj, showMsg } from '@/utils/frequency.js';
import { getUnitList, getPlantList, exportToExcel } from '@/services/stagePower.js';

import { onMounted, ref,onBeforeUnmount, provide,reactive, nextTick } from 'vue';

const visibleDia = ref(false);
provide('visibleDia', visibleDia);

// 查询电厂列表
const plantList = ref([]);
const querPlants = async () => {
  const res = await getPlantList();
  if (res.respStatus) {
    plantList.value = res.respData.dataList;
    return;
  }
  plantList.value = [];
}

const model = {key: 'plantCode', value: 'plantName'};

const pageLimit = reactive({
  pageIndex: 1,
  pageRow: 10,
  totalCount: 0,
});
provide('pageLimit', pageLimit);

const tableData = ref([]);

// 查询条件
const param = reactive({
  plantCode: null, // 所属电厂
  yearType: null, // 类型
  capacity: null, // 机组容量
  start: null, // 投运时间-开始
  end: null, // 投运时间-结束
  periods: null, // 年份
})
provide('param', param);

// 表格的加载动画
const tableLoading = ref(true);

// 查询机组列表
const queryUnitList = async () => {
  if (!param) param = {};
  param.pageLimit = pageLimit;
  tableLoading.value = true;
  const res = await getUnitList(param);
  if (!res.respStatus) return showMsg(res.respMessage);

  const list = res.respData.dataList;
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      switch(item.YEAR_TYPE) {
        case '1': item.YEAR_TYPE_T = '丰水年';break;
        case '2': item.YEAR_TYPE_T = '平水年';break;
        case '3': item.YEAR_TYPE_T = '枯水年';break;
      }
      switch(item.USE_STATUS) {
        case '0': item.USE_STATUS_T = '无效';break;
        case '1': item.USE_STATUS_T = '有效';break;
      }
    }

  tableData.value = list;
  nextTick(() => {
    tableLoading.value = false;
  })
  copyAttr(pageLimit, res.respData.pageLimit);
}

// 导出机组列表
const exportUnitList = async () => {
  if (!param) param = {};
  const res = await exportToExcel(param);
  const downloadLink = document.createElement('a');
  downloadLink.href = window.URL.createObjectURL(res);
  downloadLink.download = '水电三段式.xlsx';
  downloadLink.style.display = 'none';
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
}

// 动态调整表格的高度
const tableHeight = ref(795);
const showTable = ref();
const refreshTableMaxHeight = () => {
  const parentHeight = showTable?.value.offsetHeight;
  tableHeight.value = parentHeight - 156;
};

// 弹窗属性，0：添加，1：修改
const operFlag = ref(0);
provide('operFlag', operFlag);

// 表格所选中的列的集合
const selectedList = ref([]);
const handleSelectionChange = (list) => {
  selectedList.value = list;

  if (list.length == 1) {
    const row = list[0];
    const plant = {
      code: row.PLANT_CODE,
      unitName: row.UNIT_NAME,
      yearType: row.YEAR_TYPE,
      periods: row.PERIODS,
    }
    const type = {
      generator1: row.GENERATOR1,
      generator2: row.GENERATOR2,
      generator3: row.GENERATOR3,
    }
    const param = {
      capacity: row.CAPACITY,
      runDate: row.RUN_DATE,
      fixHours: row.FIX_HOURS,
    }
    const month12 = getMonth12();
    for (let i = 0; i < month12.length; i++) {
      const month = {
        expect: row['EXPECT_POWER_' + (i + 1)], 
        average: row['AVERAGE_POWER_' + (i + 1)], 
        forced: row['FORCED_POWER_' + (i + 1)], 
      }
      month12[i] = month;
    }
    selectedRow.plant = plant;
    selectedRow.type = type;
    selectedRow.param = param;
    selectedRow.month = month12;
  } 
  selectedRow.length = list.length;
}

const getMonth12 = () => {
  let month12 = []; 
  for (let i = 0; i < 12; i++) month12.push({
    expect: null, // 期望出力
    average: null, // 平均出力
    forced: null, // 强迫出力
  });
  return month12;
}
const month12 = getMonth12();

// 被选中的单行
const selectedRow = reactive({
  plant: {
    code: null,
    unitName: null,
    yearType: null,
    periods: null,
  }, // 所属电厂
  type: {
    generator1: null,
    generator2: null,
    generator3: null,
  }, // 发电类型
  param: {
    capacity: null,
    runDate: null,
    fixHours: null,
  }, // 基本参数
  month: month12, // 12个月份
});
const resetSelectedRow = () => {
  resetObj(selectedRow.plant);
  resetObj(selectedRow.type);
  resetObj(selectedRow.param);

  selectedRow.month = getMonth12();
}
provide('selectedRow', selectedRow);

onMounted(() => {
  window?.addEventListener("resize", refreshTableMaxHeight);
  refreshTableMaxHeight();
  querPlants();
  queryUnitList();
});
onBeforeUnmount(() => {
  window?.removeEventListener("resize", refreshTableMaxHeight);
});

</script>

<style lang="scss" scoped>
.showTable {
  width: 100%;
  .table {
    padding-bottom: 26px;
    overflow: auto;
    width: 100%;
  }
  .condition {
    padding: 10px;
  }
  :deep(.el-table thead.is-group th.el-table__cell) {
    padding: 5px;
    background-color: #4090e7;
    .cell {
      color: #fff;
    }
  }
  .page {
    z-index: 1;
    bottom: 41px;
    width: 100%;
    position: absolute;
    padding-right: 10px;
    background-color: #FFF;
  }
}

</style>
